package breadbox.client.files;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * Object that represents a file chunk in the system
 * @author Forrest
 *
 */
public class FileChunk extends Chunk {

	private static final long serialVersionUID = -1780563099205830914L;

	/**
	 * Constructs a new Chunk
	 * @param d byte[] Byte array representing file data
	 */
	public FileChunk (byte[] d, int i, long id, String filename) {
		this(d, i, id, filename, false, false);
	}
	
	public FileChunk(byte[] b) throws IOException, ClassNotFoundException {
		// get chunk from byte[]
		byte[] b_in = b.clone();
		ByteArrayInputStream byte_in = new ByteArrayInputStream(b_in);
		ObjectInputStream object_in = new ObjectInputStream(byte_in);
		FileChunk k = (FileChunk)object_in.readObject();
		object_in.close();
		byte_in.close();
		
		// get fields from chunk
		if (k != null) {
			this.data = k.getData();
			this.id = k.getID();
			this.index = k.getIndex();
			this.filename = k.getFilename();
			this.total = k.getTotal();
		}
	}

	public FileChunk(byte[] d, int index, long id,
			String filename, boolean encryption, boolean publicfile) {
		byte[] data = d.clone();
		if (encryption) {
			data = encrypt(data); 
		}
		this.data = data;
		this.id = id;
		this.index = index;
		this.filename = filename;
		this.total = 0;
		this.encryption = encryption;
		this.publicfile = publicfile;
	}
}